<template>
  <AiFeatureBase
    title="知识问答"
    icon="🧠"
    description="知识渊博的AI助手，回答各种问题"
    :examples="examples"
    :modes="qaModes"
    :quick-actions="quickActions"
    :stats="stats"
    :is-loading="isLoading"
    support-voice
    support-image
    input-placeholder="请输入您的问题..."
    @send="handleSend"
    @select-example="handleSelectExample"
    @select-mode="handleSelectMode"
    @quick-action="handleQuickAction"
    @voice-input="handleVoiceInput"
    @image-select="handleImageSelect"
  >
    <template #content>
      <AiMessageList
        :messages="messages"
        :is-typing="isTyping"
        :typing-text="typingText"
        welcome-icon="🧠"
        welcome-title="知识问答助手"
        welcome-message="我是您的知识问答助手，可以回答各种学科的问题。请随时向我提问！"
        ai-icon="🧠"
        :quick-start="quickStartItems"
        @quick-start="handleQuickStart"
        @like="handleLike"
        @dislike="handleDislike"
        @share="handleShare"
        @retry="handleRetry"
        @preview-image="handlePreviewImage"
      />
    </template>

    <template #settings>
      <div class="settings-content">
        <div class="setting-group">
          <h4>回答详细程度</h4>
          <van-radio-group v-model="settings.detailLevel">
            <van-radio name="simple">简洁回答</van-radio>
            <van-radio name="detailed">详细回答</van-radio>
            <van-radio name="comprehensive">全面回答</van-radio>
          </van-radio-group>
        </div>

        <div class="setting-group">
          <h4>专业领域</h4>
          <van-checkbox-group v-model="settings.domains">
            <van-checkbox name="science">科学技术</van-checkbox>
            <van-checkbox name="history">历史文化</van-checkbox>
            <van-checkbox name="literature">文学艺术</van-checkbox>
            <van-checkbox name="life">生活常识</van-checkbox>
          </van-checkbox-group>
        </div>

        <div class="setting-group">
          <h4>语言风格</h4>
          <van-radio-group v-model="settings.style">
            <van-radio name="formal">正式</van-radio>
            <van-radio name="casual">轻松</van-radio>
            <van-radio name="academic">学术</van-radio>
          </van-radio-group>
        </div>

        <div class="setting-group">
          <h4>其他选项</h4>
          <van-switch v-model="settings.enableHistory" size="20" />
          <span class="setting-label">保存对话历史</span>
          <br><br>
          <van-switch v-model="settings.enableStream" size="20" />
          <span class="setting-label">启用流式输出</span>
        </div>
      </div>
    </template>
  </AiFeatureBase>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant'
import AiFeatureBase from '@/components/AiFeatureBase.vue'
import AiMessageList from '@/components/AiMessageList.vue'
import { useAIService, AIServiceType } from '@/utils/aiServiceManager'
import { getUserInfo } from '@/utils/auth'

// AI服务
const aiService = useAIService()

// 响应式数据
const messages = ref<any[]>([])
const isLoading = ref(false)
const isTyping = ref(false)
const typingText = ref('AI正在思考中...')
const currentMode = ref('')

// 设置
const settings = ref({
  detailLevel: 'detailed',
  domains: ['science', 'history'],
  style: 'casual',
  enableHistory: true,
  enableStream: true
})

// 统计数据
const stats = ref([
  { label: '今日问答', value: '12' },
  { label: '准确率', value: '98%' },
  { label: '响应时间', value: '1.2s' }
])

// 问答模式
const qaModes = ref([
  {
    id: 'general',
    name: '通用问答',
    description: '回答各种常见问题',
    icon: '🤔'
  },
  {
    id: 'academic',
    name: '学术问答',
    description: '专业学术问题解答',
    icon: '🎓'
  },
  {
    id: 'science',
    name: '科学技术',
    description: '科学技术相关问题',
    icon: '🔬'
  },
  {
    id: 'history',
    name: '历史文化',
    description: '历史文化知识问答',
    icon: '📚'
  }
])

// 示例问题
const examples = ref([
  { text: '什么是人工智能？', icon: '🤖' },
  { text: '太阳系有几颗行星？', icon: '🌍' },
  { text: '中国古代四大发明是什么？', icon: '📜' },
  { text: '如何学习编程？', icon: '💻' },
  { text: '健康饮食的原则有哪些？', icon: '🥗' }
])

// 快速操作
const quickActions = ref([
  { id: 'clear', text: '清空对话', icon: 'delete-o', type: 'default' },
  { id: 'export', text: '导出对话', icon: 'down', type: 'default' },
  { id: 'favorite', text: '收藏问题', icon: 'star-o', type: 'default' }
])

// 快速开始项目
const quickStartItems = ref([
  { text: '科学知识', icon: '🔬' },
  { text: '历史文化', icon: '📚' },
  { text: '技术问题', icon: '💻' },
  { text: '生活常识', icon: '🏠' }
])

// 用户信息
const userInfo = computed(() => getUserInfo())

// 方法
const handleSend = async (text: string) => {
  if (!text.trim() || isLoading.value) return

  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    type: 'user' as const,
    content: text,
    timestamp: Date.now()
  }
  messages.value.push(userMessage)

  // 添加AI消息占位符
  const aiMessage = {
    id: Date.now() + 1,
    type: 'ai' as const,
    content: '',
    timestamp: Date.now(),
    isLoading: true
  }
  messages.value.push(aiMessage)

  isLoading.value = true
  isTyping.value = true

  try {
    let accumulatedText = ''
    
    const response = await aiService.knowledgeQA(
      {
        userId: userInfo.value?.id || 1,
        message: text,
        mode: currentMode.value,
        options: {
          detailLevel: settings.value.detailLevel,
          domains: settings.value.domains,
          style: settings.value.style
        },
        enableStream: settings.value.enableStream
      },
      {
        onStart: () => {
          typingText.value = 'AI正在分析问题...'
        },
        onMessage: (content: string, isComplete: boolean) => {
          accumulatedText += content
          const messageIndex = messages.value.length - 1
          messages.value[messageIndex] = {
            ...messages.value[messageIndex],
            content: accumulatedText,
            isLoading: false,
            isTyping: !isComplete
          }
        },
        onComplete: (fullContent: string) => {
          const messageIndex = messages.value.length - 1
          messages.value[messageIndex] = {
            ...messages.value[messageIndex],
            content: fullContent,
            isLoading: false,
            isTyping: false
          }
          isTyping.value = false
        },
        onError: (error: any) => {
          console.error('知识问答失败:', error)
          const messageIndex = messages.value.length - 1
          messages.value[messageIndex] = {
            ...messages.value[messageIndex],
            content: '抱歉，我现在无法回答您的问题。请稍后再试。',
            isLoading: false,
            error: error.message || '服务暂时不可用'
          }
          isTyping.value = false
        }
      }
    )

    // 如果没有使用流式输出，直接设置结果
    if (!settings.value.enableStream && response.success) {
      const messageIndex = messages.value.length - 1
      messages.value[messageIndex] = {
        ...messages.value[messageIndex],
        content: response.data || '回答获取成功，但内容为空。',
        isLoading: false
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    showToast('发送失败，请重试')
  } finally {
    isLoading.value = false
    isTyping.value = false
  }
}

const handleSelectExample = (example: any) => {
  const text = typeof example === 'string' ? example : example.text
  handleSend(text)
}

const handleSelectMode = (mode: any) => {
  currentMode.value = mode.id
  showToast(`已切换到${mode.name}模式`)
}

const handleQuickAction = (action: any) => {
  switch (action.id) {
    case 'clear':
      messages.value = []
      showToast('对话已清空')
      break
    case 'export':
      exportConversation()
      break
    case 'favorite':
      showToast('功能开发中...')
      break
  }
}

const handleQuickStart = (item: any) => {
  const questions = {
    '科学知识': '请介绍一下量子物理的基本概念',
    '历史文化': '中国古代丝绸之路的历史意义是什么？',
    '技术问题': '什么是机器学习？它有哪些应用？',
    '生活常识': '如何保持健康的生活方式？'
  }
  
  const question = questions[item.text as keyof typeof questions] || item.text
  handleSend(question)
}

const handleVoiceInput = () => {
  showToast('语音输入功能开发中...')
}

const handleImageSelect = () => {
  showToast('图片识别功能开发中...')
}

const handleLike = (message: any) => {
  message.liked = !message.liked
  if (message.liked) {
    message.disliked = false
    showToast('感谢您的反馈！')
  }
}

const handleDislike = (message: any) => {
  message.disliked = !message.disliked
  if (message.disliked) {
    message.liked = false
    showToast('我们会改进回答质量')
  }
}

const handleShare = (message: any) => {
  if (navigator.share) {
    navigator.share({
      title: '知识问答',
      text: message.content
    })
  } else {
    navigator.clipboard.writeText(message.content)
    showToast('内容已复制到剪贴板')
  }
}

const handleRetry = (message: any) => {
  // 找到对应的用户消息并重新发送
  const messageIndex = messages.value.indexOf(message)
  if (messageIndex > 0) {
    const userMessage = messages.value[messageIndex - 1]
    if (userMessage.type === 'user') {
      handleSend(userMessage.content)
    }
  }
}

const handlePreviewImage = (url: string, urls?: string[]) => {
  // 图片预览逻辑
  console.log('预览图片:', url, urls)
}

const exportConversation = () => {
  const content = messages.value
    .map(msg => `${msg.type === 'user' ? '用户' : 'AI'}: ${msg.content}`)
    .join('\n\n')
  
  const blob = new Blob([content], { type: 'text/plain' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `知识问答-${new Date().toLocaleDateString()}.txt`
  a.click()
  URL.revokeObjectURL(url)
  showToast('对话已导出')
}

// 生命周期
onMounted(async () => {
  // 加载用户统计数据
  try {
    const userStats = await aiService.getUserStats(userInfo.value?.id || 1)
    if (userStats.knowledgeQA) {
      stats.value = [
        { label: '今日问答', value: userStats.knowledgeQA.todayCount || '0' },
        { label: '准确率', value: `${userStats.knowledgeQA.accuracy || 98}%` },
        { label: '响应时间', value: `${userStats.knowledgeQA.avgResponseTime || 1.2}s` }
      ]
    }
  } catch (error) {
    console.error('加载用户统计失败:', error)
  }
})
</script>

<style scoped>
.settings-content {
  padding: 0;
}

.setting-group {
  margin-bottom: 24px;
}

.setting-group h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
  margin: 0 0 12px 0;
}

.setting-label {
  margin-left: 8px;
  font-size: 14px;
  color: #374151;
}

.van-radio,
.van-checkbox {
  margin-bottom: 8px;
}
</style>
